﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Data.SqlClient;

namespace TM_Server
{
    class Rev2Client_SendMessage
    {
        #region 全局变量部分

        NetworkStream Stream;          //保存与客户的通信句柄
        String Info;                   //保存用户登陆信息
        String Username = "";          //保存QQ（用户名）
        String Password = "";          //保存登陆密码
        String FG_Info = "";           //保存用户的分组信息还有好友信息
        private String Ip = "";        //保存上线者IP
        public delegate void Pt();     //创建委托用于刷窗体
        String PID;                    //用户唯一标识
        SqlConnection Connection = new SqlConnection("Data Source=(local);Initial Catalog=TM_Setting_Infomation;Persist Security Info=True;User ID=sa;Password=songna0917");

        #endregion

        #region 构造函数部分

        public Rev2Client_SendMessage(NetworkStream Stream , String Info , String Ip)
        {
            this.Info = Info;
            this.Stream = Stream;
            this.judge2QQ();
            this.Ip = Ip;
        }

        #endregion

        #region 接收的用户登陆字符串，并且合理拆分

        /*
         * 此方法用来将接收的用户登陆字符串
         * 进行合理拆分，最终得到用户名，密码
         * 并传入下一个过程，进入数据库查询
         */
        public void judge2QQ()
        {
            String[] Collect = this.Info.Split('|');
            String[] Result_Collect;  //用来保存用户名密码

            //如果传递过来的登录信息分离后，结构等于2
            if (Collect.Length == 2)
            {
                try
                {
                    Result_Collect = Collect[0].Split(',');
                    Username = Result_Collect[0].Trim();    //得到用户名
                    Password = Result_Collect[1].Trim();    //得到密码
                    //MessageBox.Show("用户名：" + Username + " 密码：" + Password + "状态：" + Collect[1]);
                    try
                    {
                        int Line_Length = this.GetOnlineResult();
                        if (Line_Length == 0)
                        {
                            //登陆成功的同时也将分组，好友信息发过去
                            Stream.Write(Encoding.Default.GetBytes(this.FG_Info), 0, Encoding.Default.GetBytes(this.FG_Info).Length);
                            Stream.Flush();
                            //将该用户的Stream保存
                            Save_UserStream sus = new Save_UserStream();
                            sus.Tm_number = Username.Trim();  //打入用户ID
                            sus.Stream = this.Stream;
                            //打入集合
                            Globle.list.Add(sus);
                            Globle.Main_f.User_Show.BeginInvoke(new Pt(this.Paint_It));  //将用户上线命令传入
                        }
                        else
                        {
                            Stream.Write(Encoding.Default.GetBytes("NO"), 0, Encoding.Default.GetBytes("OK").Length);
                            Stream.Flush();
                            //MessageBox.Show("帐号或者密码错误！");
                        }
                    }
                    catch(Exception ex)
                    {
                         MessageBox.Show("数据库分析出错了！");
                    }

                }
                catch(Exception ex)
                {
                    MessageBox.Show("拆分出错了！");
                }
            }
        }

        #endregion

        #region 连接数据库，并且判断用户的用户名和密码是否为正确

        /*
         * 此方法为连接数据库，并且判断用户的用户名
         * 和密码是否为正确，如果正确 返回 0 ，否则返回1
         */
        public int GetOnlineResult()
        {
            try
            {
                //拼接字符串
                String CMD = "SELECT User_QQ_Number,User_Password FROM TM_User ";
                CMD += "Where User_QQ_Number = " + this.Username + " ";
                CMD += "and User_Password = '" + this.Password +"'";
                Connection.Open();
                SqlCommand Command = new SqlCommand(
                    CMD,
                    Connection);
                String i = Command.ExecuteScalar().ToString();
                if (i.Length >= 1)
                {
                    //查询相关的ID信息
                    CMD = "SELECT User_Id FROM TM_User ";
                    CMD += "Where User_QQ_Number = " + this.Username + " ";
                    CMD += "and User_Password = '" + this.Password + "'";
                    Command = new SqlCommand(CMD, Connection);
                    this.PID = Command.ExecuteScalar().ToString();  //得到唯一ID
                    this.Search2GROUP_Friend(this.PID);
                    return 0;
                }
                else
                {
                    return 1;
                }
            }
            catch(Exception ex)
            {
                return 1;
                MessageBox.Show("连接数据库出错！");
            }

        }

        #endregion

        #region 根据传递进来的Id，来查询根据此ID的分组信息，还有好友信息

        /*
         * 此方法用来根据传递进来的Id
         * 来查询根据此ID的分组信息，还有好友信息
         */
        public void Search2GROUP_Friend(String PID)
        {
            try
            {
                this.Search2User_Info();  //调用查询用户详细信息方法
                String CMD = "SELECT Group_Name,Group_Id FROM TM_Group WHERE Group_UserId = " + this.PID;
                SqlDataAdapter da = new SqlDataAdapter(CMD, "Data Source=(local);Initial Catalog=TM_Setting_Infomation;Persist Security Info=True;User ID=sa;Password=songna0917");
                DataSet ds = new DataSet();
                da.Fill(ds);  //填充数据集
                foreach (DataTable table in ds.Tables)
                {
                    //遍历表中的行（数据行）
                    foreach (DataRow row in table.Rows)
                    {
                        //开始遍历每个数据行的数据列
                        this.FG_Info += row[0].ToString().Trim() + "|*|";
                        //拼接查询好友字符串
                        CMD = "SELECT Friend_UserId FROM TM_Friend WHERE Friend_GroupId = " + row[1].ToString();
                        //创建SQL适配器，来查询好友
                        SqlDataAdapter da_f = new SqlDataAdapter(CMD, "Data Source=(local);Initial Catalog=TM_Setting_Infomation;Persist Security Info=True;User ID=sa;Password=songna0917");
                        DataSet ds_f = new DataSet();
                        da_f.Fill(ds_f);  //填充数据集
                        foreach(DataTable tables in ds_f.Tables)
                        {
                            foreach(DataRow rows in tables.Rows)
                            {
                                String CMD_FN = "SELECT User_NickName,User_Face,User_Pro,User_QQ_Number FROM TM_User WHERE User_Id = " + rows[0];
                                SqlDataAdapter adapater = new SqlDataAdapter(CMD_FN, "Data Source=(local);Initial Catalog=TM_Setting_Infomation;Persist Security Info=True;User ID=sa;Password=songna0917");
                                DataSet sd1 = new DataSet();
                                adapater.Fill(sd1);  //填充记录集
                                foreach(DataTable dtb in sd1.Tables)
                                {
                                    foreach(DataRow dtr in dtb.Rows)
                                    {
                                        //好友昵称 + 好友头像编号 + 好友个性签名 + 好友QQ
                                        this.FG_Info += "&|&" + dtr[0].ToString().Trim() + "%**%" + dtr[1].ToString().Trim() + "%**%" + dtr[2].ToString().Trim() + "%**%" + dtr[3].ToString().Trim();
                                    }
                                }
                            }
                        }
                        //最后添加分组完成分隔符
                        this.FG_Info += "*||*";
                    }
                }
                //MessageBox.Show(this.FG_Info);
            }
            catch(Exception ex)
            {
                MessageBox.Show("调试分组信息出现错误：" + ex.Message);
            }
        }

        #endregion

        #region 查找用户登陆的相关信息

        /*
         * 此方用来首先查找用户登陆的相关信息
         * 包括用户的昵称，个人签名，详细信息，头像编号
         */
        public void Search2User_Info()
        {
            try
            {
                String CMD = "SELECT * FROM TM_User WHERE User_Id = " + this.PID;
                //创建适配器
                SqlDataAdapter dp = new SqlDataAdapter(CMD, "Data Source=(local);Initial Catalog=TM_Setting_Infomation;Persist Security Info=True;User ID=sa;Password=songna0917");
                DataSet ds = new DataSet();
                dp.Fill(ds);  //填充记录集
                foreach (DataTable tables in ds.Tables)
                {
                    foreach (DataRow rows in tables.Rows)
                    {
                        try
                        {
                            this.FG_Info += rows["User_NickName"].ToString().Trim() + "*||*";
                            this.FG_Info += rows["User_Pro"].ToString().Trim() + "*||*";
                            this.FG_Info += rows["User_Info"].ToString().Trim() + "*||*";
                            this.FG_Info += rows["User_Face"].ToString().Trim() + "*||*";
                        }
                        catch(Exception ex)
                        {
                            MessageBox.Show("赋值用户详细信息的时候出现错误：" + ex.Message);
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("开始查询用户详细信息的时候出现错误：" + ex.Message);
            }
        }

        #endregion

        #region 用于依据委托来将内容打入主窗体的LISTVIEW

        /*
         * 此方法用于依据委托来将内容
         * 打入主窗体的LISTVIEW
         */
        public void Paint_It()
        {
            int _IsShow = 0;  //标志位，用来判定是否已经显示过上线 0 | 没显示过， 1 | 显示过
            for (int i = 0; i < Globle.Main_f.User_Show.Items.Count; i++)
            {
                if (Globle.Main_f.User_Show.Items[i].Text == this.Username)
                {
                    _IsShow = 1;
                    return;
                }
            }
            //如果没显示过
            if (_IsShow == 0)
            {
                Globle.Main_f.User_Show.Items.Add(this.Username, this.Username, 0);
                Globle.Main_f.User_Show.Items[this.Username].SubItems.Add(this.Ip);
                Globle.Main_f.User_Show.Items[this.Username].SubItems.Add("4000");
            }
        }

        #endregion

    }
}
